package com.sumainfor.pc.epc.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ListMapMergeUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.ReceiveMapper;
import com.sumainfor.pc.epc.dao.UtilsMapper;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.ReceiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: zhlu
 * @Date: 2018/11/3 20:45
 * @Description:
 */
@Service
public class ReceiveServiceImpl implements ReceiveService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(ReceiveServiceImpl.class);
    @Autowired
    private ReceiveMapper receiveMapper;
    @Autowired
    UtilsMapper utilsMapper;

    String UUID = null;

    @Autowired
    private ZzuulFeign zzuulFeign;

    /**
     * 分页查询领用单列表
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> getReceiveList(Map<String, Object> params) {
        List<Map<String, Object>> result = receiveMapper.getReceiveList(params);//查询到领用单编号
        if(result.size()>0){
            JsonResult jsonResult=zzuulFeign.getAllUserIdAndName();
            List<Map<String,Object>>getAllUserIdAndName=(List<Map<String,Object>>)jsonResult.getResult();
            result= ListMapMergeUtil.ListMergeUtils(result,getAllUserIdAndName,"userId");
        }
        return result;
    }

    /**
     * 查询领用单总数
     *
     * @param params
     * @return
     */
    @Override
    public Integer getReceiveListCount(Map<String, Object> params) {
        return receiveMapper.getReceiveListCount(params);
    }

    /**
     * 由PC后台系统发起领用单 新增领用单主表记录
     *
     * @param params
     * @return
     */
    @Override
    public Integer addReceivePC(Map<String, Object> params) {
        Integer result = 0;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "RecId");
                    put("database", Constants.DATA_SOURCE_TCEPC);
                    put("surface", "tcepc_receive");
                }});
                if (uuid != null) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("re", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("re", 0);
                }
                System.out.println("前端传递的参数:" + params);
                params.put("SysUserId", ContextUtils.getUserId());//领用单申请人
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("IfState", "1");//是否被领用 1:未领用 2:领取
                params.put("RecType", "2");// 1:维修领用单 2:备件领用单
                params.put("RecId", UUID);
                params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                result = receiveMapper.addReceivePC(params);
                if (result > 0) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("data");
                    for (int i = 0; i < list.size(); i++) {
                        params.putAll(list.get(i));
                        System.out.println("params:" + params);
                        receiveMapper.addReceiveInfoPC(params);

                        //成功
                        CustomMap data = CustomMap.create("MeType", 7)
                                .put("Title", "新接收的领用单")
                                .put("Content", HtmlUtil.stringToHTML("您收到一条新的备件领用单，请及时处理！；", "", Color.blue))
                                .put("by", ContextUtils.getUserId())
                                .put("IfJump", 1)
                                .put("Neturl", "/sys-engineeringmanager/buyer")
                                .put("term", 3);
                        zzuulFeign.AddMessage(data);


                    }
                    System.out.println("list:" + list);
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }

        return result;
    }

    /**
     * 查询领用单关联对应的领用单商品
     */
    @Override
    public List<Map<String, Object>> getReceiveGoodList(Map<String, Object> params) {
        return receiveMapper.getReceiveGoodList(params);
    }
}
